package com.nuanshui.heatedloan.controller.display.users;

import com.aipg.rnp.RNPARET;
import com.aipg.rnp.RNPCRETCODE;
import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.credit.facade.AllinPayAuthService;
import com.nuanshui.heatedloan.credit.pay.PayRequest;
import com.nuanshui.heatedloan.msgcenter.facade.VerificationFacade;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.constant.SmsTypeConstant;
import com.nuanshui.heatedloan.controller.BaseController;
import com.nuanshui.heatedloan.controller.display.users.apply.ControllerHelper;
import com.nuanshui.heatedloan.msgcenter.model.AliSmsSecurityCodeTemplateEnum;
import com.nuanshui.heatedloan.msgcenter.model.VeriCodeResult;
import com.nuanshui.heatedloan.userinfo.facade.UserQueryService;
import com.nuanshui.heatedloan.userinfo.facade.UserService;
import com.nuanshui.heatedloan.userinfo.form.UserForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


/**
 * 短信验证码验证码
 * @author Gonzo
 * @date 2016年11月8日
 */
@RestController
@RequestMapping("sms/")
public class SmsController extends BaseController{

	@Reference(url = GlobalParam.MSGCENTER_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version=GlobalParam.MSGCENTER_DUBBO_SERVER_VERSION )
	private VerificationFacade veriFacade;
	
	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserService userService;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserQueryService userQueryService;

	@Reference(url = GlobalParam.CREDIT_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version=GlobalParam.CREDIT_DUBBO_SERVER_VERSION )
	private AllinPayAuthService allinPayAuthService;
	
	@RequestMapping(value = "/sendSmsByType",method = RequestMethod.POST)
	public String sendMessageByType(@Validated @ModelAttribute UserForm form, Errors errors, Integer length, Integer smsType){
		//校验错误
		ControllerHelper.checkException(errors);

		UserAgent userAgent=getUserAgent();

		if(userAgent==null || SysStringUtils.isEmpty(userAgent.getSafeToken()))
			return error("没有权限");

		VeriCodeResult result=null;

		switch (smsType) {
			case SmsTypeConstant.SMSTYPECONSTANT_SIGN://注册发送验证码
				result=veriFacade.generateCode(form.getMobile(), AliSmsSecurityCodeTemplateEnum.ALI_SIGN, length);
				break;

			case SmsTypeConstant.SMSTYPECONSTANT_DYNAMIC_PWD://忘记密码的验证码
				if(!userService.isRegistered(form.getMobile())){
					throw new BizException(GlobalErrorCode.UNKNOWN, "手机号未注册");
				}

				result=veriFacade.generateCode(form.getMobile(), AliSmsSecurityCodeTemplateEnum.ALI_DYNAMIC_PWD, length);
				break;

			case SmsTypeConstant.SMSTYPECONSTANT_UPDATE_PWD://修改密码的验证码
				if(!userService.isRegistered(form.getMobile())){
					throw new BizException(GlobalErrorCode.UNKNOWN, "手机号未注册");
				}
				result=veriFacade.generateCode(form.getMobile(), AliSmsSecurityCodeTemplateEnum.ALI_UPDATE_PWD, length);
				break;
			case SmsTypeConstant.SMSTYPECONSTANT_DYNAMIC_DYNAMICORREGI://获取动态登录的验证码
				result=veriFacade.generateCode(form.getMobile(), AliSmsSecurityCodeTemplateEnum.ALI_DYNAMIC_DYNAMICORREGI, length);
				break;
			case  SmsTypeConstant.SET_PAY_PASSWORD ://设置支付密码短信
				String phone =  userService.getUserPhone(getCurrentUser().getId());
				if(!StringUtils.isEmpty(phone)) {
					result=veriFacade.generateCode(phone, AliSmsSecurityCodeTemplateEnum.SET_PAY_PASSWD, length);
				}else {
					return error("手机号不存在");
				}
				break;
			case SmsTypeConstant.SMSTYPECONSTANT_PHONE_AUTH:  //手机验证的接口
				result=veriFacade.generateCode(form.getMobile(), AliSmsSecurityCodeTemplateEnum.ALI_PHONE_AUTH, length);
				break;
			case SmsTypeConstant.SET_REPAYMENT_PASSWORD : //设置还款支付密码
				result=authRepayUserAccount();
			    break;
			case SmsTypeConstant.SUBMIT_ORDER:  //提交订单
				result=veriFacade.generateCode(form.getMobile(),AliSmsSecurityCodeTemplateEnum.SUBMIT_ORDER,length);
		}
		
		return success(result);
	}

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;

	private VeriCodeResult authRepayUserAccount() {

		final String orderId = getRequest().getParameter("orderId");

		final String mixCardNo = getRequest().getParameter("mixCardNo");

		final String userId=getCurrentUser().getId();

		if (SysStringUtils.isNotEmpty(orderId)) {

			taskExecutor.execute(new Runnable() {
				@Override
				public void run() {
					PayRequest request = new PayRequest();
					request.setOrderNo(orderId);
					request.setMixCardNo(mixCardNo);
					request.setUserId(userId);
					RNPARET result = allinPayAuthService.authRepayUserAccount(request);

					if (result.getRET_CODE().equals(RNPCRETCODE.VERYIFY_SUCCESS)) {

					}
				}
			});

			return new VeriCodeResult(true, 4);
		}

		return null;
	}

	public static void main(String[] args) {

	}

}
